<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px; position: relative;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add">新建</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">系统参数</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ roleText }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100%;">
        <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
        <el-card style="box-shadow: none; width: 65%; margin-right: 10px;">
          <el-form :model="codeForm" style="width: 100%;">
            <el-form-item label="" prop="roleName">
              <el-input v-model="codeForm.bizName"
                style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                class="idoo-details-input" placeholder="编码标题：例如：SYSTEM_TABLE_STATUS"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <el-form-item label="编码类型">
                  <el-input v-model="codeForm.bizType"
                    style="width: 100%; height: 40px; line-height: 60px; width: 70%; padding: 10px;"
                    class="idoo-details-input" placeholder="编码  例如：SYSTEM_TABLE_STATUS"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="码值">
                  <el-input v-model="codeForm.bizValue" style="width: 100%;" class="idoo-details-input"
                    placeholder="例如：0、1"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-input v-model="codeForm.status" style="width: 100%;" class="idoo-details-input"
                    placeholder=""></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input v-model="codeForm.remark" style="width: 100%;" class="idoo-details-input"
                    placeholder="例如：0、1"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 右侧：修改记录区域，保持背景色 -->
        <div style="width: 35%; padding: 10px;">
          <!-- 修改记录内容 -->
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled, RefreshLeft } from '@element-plus/icons-vue';
import router from '@/router';
import { ElMessageBox } from 'element-plus';
import { _getSystemCodeById, _saveSystemCode, _updateSystemCode } from '@/api/generic/code/code-api';
import type { CodeInfo } from '@/api/generic/code/code-api';

const route = useRoute();
const roleText = ref("");
const isFormChanged = ref(false);
const originalFormData = ref<RoleForm>({});
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).catch(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
// 定义表单数据类型
interface RoleForm {
  id?: string;
  bizType?: string;
  bizName?: string;
  remark?: string;
  status?: string;
  bizValue?: string;
}

interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

const routParams = route.query;
// 初始化表单数据
const codeForm = ref<RoleForm>({
  id: '',
  bizType: '',
  bizName: '',
  remark: '',
  status: '',
  bizValue: '',
})
const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(codeForm.value));
  roleText.value = codeForm.value.bizName || '新建';
  isFormChanged.value = false;
}

// 监听表单变化
watch(() => codeForm.value, (newVal) => {
  console.log('newVal', newVal);
  console.log('originalFormData.value', originalFormData.value);
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

//初始化加载数据
onMounted(async () => {
  //获取用户数据
  if (routParams.id) {
    //如果当前不是通过主界面菜单跳转，不加载第一个菜单路由，指定路由加载
    _getSystemCodeById(routParams.id.toString()).then(res => {
      codeForm.value = res.data;
      originalFormData.value = JSON.parse(JSON.stringify(res.data));
      roleText.value = codeForm.value.bizName || '';
    })
  } else {
    codeForm.value = {
      id: '',
      bizType: '',
      bizName: '',
      remark: '',
      status: '',
      bizValue: '',
    }
    originalFormData.value = JSON.parse(JSON.stringify(codeForm.value));
    roleText.value = '新建'
  }
});

// 保存处理函数
const handleSave = async () => {
  //TODO 表单校验
  const formData = {
    id: codeForm.value.id || '',
    bizType: codeForm.value.bizType || '',
    bizName: codeForm.value.bizName || '',
    bizValue: codeForm.value.bizValue || '',
    status: codeForm.value.status || '',
    remark: codeForm.value.remark || ''
  };
  try {
    const response = await (routParams.id ? _updateSystemCode(formData) : _saveSystemCode(formData));
    const res = response as unknown as ApiResponse<CodeInfo>;
    if (res && res.code === 200) {
      resetForm();
    }
  } catch (error) {
    console.error('保存失败:', error);
  }
};

// 撤销修改，还原表单
const handleRevert = () => {
  codeForm.value = JSON.parse(JSON.stringify(originalFormData.value));
};
</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}
</style>
